<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>课程资料</title>
    <link rel="stylesheet" href="js/elementui/index.css">
    <script src="js/vue.js"></script>
    <script src="js/elementui/index.js"></script>
    <script src="js/axios.min.js"></script>
    <link rel="stylesheet" href="css/ad.css">
    <style>
        .el-dialog__body {
            width: 100%;
            height: 3000px;
        }
    </style>
</head>
<body>
<div id="app">

    <el-container>
        <el-main>
            <el-row :gutter="20" type="flex">
                <el-col :span="3">
                    <div>&nbsp;</div>
                    <el-button type="primary" @click="ret">返回</el-button>
                </el-col>
                <el-col :span="3">
                    <div>&nbsp;</div>
                    <el-button type="primary"
                               @click="addChapterShow">新增章节
                    </el-button>
                </el-col>
                <el-col :span="2">
                    <div>&nbsp;</div>
                    <el-button icon="el-icon-refresh" type="primary" onclick=" window.location.reload();">刷新</el-button>

                </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-top: 20px;" label-position="left">
                <el-table

                        :data="moduleData">
                    <el-table-column type="expand">
                        <template slot-scope="props">
                            <my-table :module-data="props.row.children"></my-table>
                        </template>
                    </el-table-column>
                    <el-table-column
                            label="章节名称"
                            prop="chaName">
                    </el-table-column>

                    <el-table-column
                            label="模块操作">
                        <template slot-scope="scope">
                            <!-- <el-button type="primary" icon="el-icon-edit"></el-button>-->
                            <el-button type="info" round size="mini" icon="el-icon-plus"
                                       @click="addChapterShow(scope.row)"></el-button>
                            <el-button type="danger" round size="mini" icon="el-icon-delete"
                                       @click="deleteModule(scope.row.chaId)"></el-button>
                            <el-button type="primary" round size="mini"  icon="el-icon-edit" @click="update2Show(scope.row)"></el-button>
                            <el-button round size="mini"   @click="zhTest(scope.row)">添加章节测试</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
        </el-main>
    </el-container>
    <el-dialog

            width="40%"
            :title="add.title"
            :visible.sync="add.show">
        <el-form ref="addForm" label-position="left" :model="add" label-width="80px">

            <el-form-item prop="chaName" label="章节名称">
                <el-input placeholder="请输入章节名称" v-model="add.chaName"></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="addUser">新增</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog

            width="40%"
            :title="update2.title"
            :visible.sync="update2.show">
        <el-form ref="addForm" label-position="left" :model="update2" label-width="80px">

            <el-form-item prop="chaName" label="章节名称">
                <el-input size="50px" placeholder="请输入章节名称" v-model="update2.chaName"></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="saveName">新增</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>


    <el-dialog
            width="40%"
            :title="update.title"
            :visible.sync="update.show"
    >
        <el-form ref="addForm" label-position="left" :model="update" label-width="80px">

            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="视频" name="first">
                    <el-form-item prop="chaName" label="章节名称">
                        <el-input v-model="update.chaName"></el-input>
                    </el-form-item>
                    <el-form-item label="视频">
                        <el-form-item>
                            <el-input type="file" id="longfile"></el-input>
                            <el-button @click="longtj()">提交</el-button>
                        </el-form-item>
                        <div v-show="update.proShow">
                            <el-progress :stroke-width="18" :text-inside="true"
                                         :percentage="update.progress"></el-progress>
                        </div>
                    </el-form-item>
                </el-tab-pane>
                <!--<el-tab-pane label="ppt" name="second">
                    <el-form-item>
                        <el-input type="file" id="pptfile"></el-input>
                        <el-button @click="ppttj()">提交</el-button>
                    </el-form-item>
                </el-tab-pane>-->
                <el-tab-pane label="文档" name="third">
                    <el-form-item>
                        <el-input type="file" id="dofile"></el-input>
                        <el-button @click="dotj()">提交</el-button>
                    </el-form-item>
                </el-tab-pane>

            </el-tabs>


            <el-form-item>
                <el-button type="primary" :disabled="update.disabled" @click="saveVideo">保存</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <el-dialog :visible.sync="chadia.show" fullscreen>
        <iframe src="/exam/examcomposition.html" style="height: 100%;width: 100%;" frameborder="0"></iframe>
        <div slot="footer" class="dialog-footer">

        </div>
    </el-dialog>
</div>

</body>
<script>

    axios.defaults.headers.common['Authorization'] = "bearer " + sessionStorage.getItem("access_token");
    axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8';
    Vue.component('my-table', {
        props: {
            moduleData: []
        },
        template: `
           <el-table :data="moduleData" >
                         <el-table-column type="expand">
                            <template slot-scope="props">
                            <my-table  :module-data="props.row.children"></my-table>
                            </template>
                        </el-table-column>
                        <el-table-column
                                label="章节名称"
                                prop="chaName">
                        </el-table-column>

                         <el-table-column
                            label="模块操作">
                        <template slot-scope="scope">
                         <el-button type="info" round size="mini"  icon="el-icon-plus" @click="addChapterShow(scope.row)"></el-button>
                           <el-button type="danger" round size="mini"  icon="el-icon-delete" @click="deleteModule(scope.row.chaId)"></el-button>

                            <el-button v-if="scope.row.children==null || scope.row.children.size==0" type="primary" round size="mini"  icon="el-icon-edit" @click="updateModuleShow(scope.row)"></el-button>
                            <el-button round size="mini"  @click="zhTest(scope.row)">添加章节测试</el-button>
                        </template>
                    </el-table-column>
                    </el-table>
        `,
        methods: {
            updateModuleShow(row) {
                v.updateModuleShow(row);
            },
            deleteModule(id) {
                v.deleteModule(id);
            },
            addChapterShow(row) {
                v.addChapterShow(row);
            },
            zhTest(row) {
                v.zhTest(row);
            }
        }
    });
    const MB = 1024 * 1024;
    var Main = {

        data() {

            return {
                chadia: {
                    show: false
                },
                form: {
                    resource: '',
                },
                activeName: 'first',
                moduleData: [],
                add: {
                    title: '',
                    courId: '',
                    chaId: '',
                    chaCourid: '',
                    show: false,
                    chaName: '',
                    chaParentid: [],

                },
                update: {
                    title: '',
                    chaId: '',
                    courId: '',
                    chaName: '',
                    chaType: '',
                    chaTime: '',
                    chalastModified: '',
                    chaSize: '',
                    chaViurl: '',
                    show: false,
                    //当前进度
                    progress: 0,
                    //进度条是否显示
                    proShow: false,
                    //百分之一代表的字节
                    complete: 0,
                    //首次进度
                    firstJd: 20,
                    disabled: false,
                    chaPpturl: '',
                    chaDocurl: ''
                },
                update2:{
                    title: '',
                    chaId: '',
                    courId: '',
                    chaName: '',
                    show: false,
                }

            };
        },
        methods: {
            ret(){
                window.location.href="course.html";
            },
            zhTest(row) {
                let chaId = row.chaId;
                localStorage.getItem("courId");
                localStorage.setItem("chaId", chaId);
                this.chadia.show = true;
            },
            dotj() {
                let file = document.getElementById("dofile").files[0];
                if (file == null) {
                    this.$message({
                        message: '请选择文档再提交',
                        type: 'warning'
                    })
                    return;
                }
                let path = "docurl/" + new Date().getTime() + file.name;
                this.update.disabled = true;
                let formData = new FormData();
                formData.append('path', path);
                formData.append('file', file);
                axios({
                    method: 'post',
                    url: '/api/oss/upload',
                    data: formData,
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    }
                }).then(res => {
                    res = res.data;
                    this.update.disabled = false;
                    if (res.success) {
                        this.$message({
                            message: '上传完成',
                            type: "success"
                        })
                        this.update.chaDocurl = res.message.path;
                    }
                })
            },
            /*ppttj() {
                let file = document.getElementById("pptfile").files[0];
                if (file == null) {
                    this.$message({
                        message: '请选择ppt再提交',
                        type: 'warning'
                    })
                    return;
                }
                let path = "ppt/" + new Date().getTime() + file.name;
                this.update.disabled = true;
                let formData = new FormData();
                formData.append('path', path);
                formData.append('file', file);
                axios({
                    method: 'post',
                    url: '/api/oss/upload',
                    data: formData,
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    }
                }).then(res => {
                    res = res.data;
                    this.update.disabled = false;
                    if (res.success) {
                        this.$message({
                            message: '上传完成',
                            type: "success"
                        })
                        this.update.chaPpturl = res.message.path;
                    }
                })
            },*/
            longtj() {
                let file = document.getElementById("longfile").files[0];
                if (file == null) {
                    this.$message({
                        message: '请选择视频文件再提交',
                        type: 'warning'
                    })
                    return;
                }
                let path = "video/" + new Date().getTime() + file.name;
                let params = new URLSearchParams();
                params.append("path", path)
                this.update.proShow = true;
                axios({
                    method: 'post',
                    url: '/api/oss/long/longUploadFirst',
                    data: params,
                }).then(res => {
                    this.update.disabled = true;
                    this.update.progress = this.update.firstJd;
                    res = res.data;
                    let uploadId = res.message;
                    this.longtjContent(uploadId, path);
                })
            },
            longtjContent(uploadId, path) {
                let file = document.getElementById("longfile").files[0];
                this.update.complete = file.size / (100 - this.update.firstJd);
                let i = 0;
                this.longWhile(file, i, uploadId, path);
            },

            longWhile(file, i, uploadId, path) {
                let end = (i + 1) * MB;
                let isNotEnd = true;
                if (end >= file.size) {
                    end = file.size
                    isNotEnd = false;
                }
                let slice = file.slice(i * MB, end);
                let formData = new FormData();
                formData.append("file", slice);
                formData.append("uploadId", uploadId);
                formData.append("path", path);
                i++;
                axios({
                    method: 'post',
                    url: '/api/oss/long/loadUploadConenet',
                    data: formData,
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    }
                }).then(res => {
                    if (slice.size >= MB && isNotEnd) {
                        this.update.progress = parseInt(end / this.update.complete) + this.update.firstJd;
                        this.longWhile(file, i, uploadId, path);
                    } else {
                        let params = new URLSearchParams();
                        params.append("uploadId", uploadId);
                        params.append("path", path);
                        axios({
                            method: 'post',
                            url: '/api/oss/long/loadUploadEnd',
                            data: params,
                        }).then(res => {
                            this.update.progress = 100;
                            this.update.disabled = false;
                            this.$message({
                                message: '上传完成',
                                type: "success"
                            })
                            res = res.data.message;
                            console.log("path", res.path);
                            console.log("lastModified", file.lastModified);
                            console.log("size", file.size);
                            console.log("type", file.type);
                            let url = URL.createObjectURL(file);
                            let audioElement = new Audio(url);

                            let duration;
                            audioElement.addEventListener("loadedmetadata", (_event) => {
                                duration = audioElement.duration;
                                var hour = parseInt((duration) / 3600);
                                var minute = parseInt((duration % 3600) / 60);
                                var second = Math.ceil(duration % 60);
                                //console.log(Math.floor(ele.duration));
                                //document.write("这段视频的时长为："+hour+"小时，"+minute+"分，"+second+"秒");
                                console.log("这段视频的时长为：" + hour + "小时，" + minute + "分，" + second + "秒")
                                this.update.chaViurl = res.path;
                                this.update.chalastModified = file.lastModified;
                                this.update.chaSize = file.size;
                                this.update.chaType = file.type;
                                this.update.chaTime = hour + "-" + minute + "-" + second;
                            });
                            /*     axios({
                                     method: 'get',
                                     url: '/api/oss/getUrl',
                                     params: {
                                         path: path
                                     },
                                 })*/
                        })
                    }
                })
                    .catch(error => {
                        console.log("错误");
                        i--;
                        longWhile(file, i, uploadId, path);
                    })
            },




            handleClick() {

            },
            //点击删除
            deleteModule(chaId) {

                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true

                }).then(() => {

                    axios({
                        method: 'delete',
                        url: '/api/teacher/chapter/' + chaId,
                    }).then(res => {
                        res = res.data;
                        if (res.success) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!',
                            });
                        } else {
                            this.$message({
                                type: 'error',
                                message: '删除失败!有子级不能删除',
                            });
                        }
                    })


                    this.queryMenu();
                    //location.reload()
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                })
            },
            saveName() {
                var courId = localStorage.getItem("courId")
                let params = new URLSearchParams()
                params.append('chaCourid', courId)
                params.append('chaId', this.update2.chaId)
                params.append('chaName', this.update2.chaName)
                this.$refs['addForm'].validate((valid) => {
                    axios({
                        method: 'post',
                        url: '/api/teacher/chapter/updateChapters',
                        data: params,
                    })
                        .then((res) => {
                            this.$message({
                                type: 'success',
                                message: '修改成功!',
                            });
                            this.update2.show = false
                            this.queryMenu()
                        }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '修改失败'
                        });
                    })
                })
            },
            update2Show(row){
                this.update2.show = true
                this.update2.chaId = row.chaId;
                this.update2.chaName = row.chaName;
            },
            //修改视频
            saveVideo() {
                var courId = localStorage.getItem("courId")
                let params = new URLSearchParams()
                params.append('chaCourid', courId)
                params.append('chaId', this.update.chaId)
                params.append('chaName', this.update.chaName)
                params.append('chaViurl', this.update.chaViurl)
                params.append('chaType', this.update.chaType)
                params.append('chalastModified', this.update.chalastModified)
                params.append('chaTime', this.update.chaTime)
                params.append('chaSize', this.update.chaSize)
                params.append('chaPpturl', this.update.chaPpturl)
                params.append('chaDocurl', this.update.chaDocurl)
                this.$refs['addForm'].validate((valid) => {
                    axios({
                        method: 'post',
                        url: '/api/teacher/chapter/updateChapters',
                        data: params,
                    })
                        .then((res) => {
                            this.$message({
                                type: 'success',
                                message: '修改成功!',
                            });
                            this.update.show = false
                            this.queryMenu()
                        }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '修改失败'
                        });
                    })
                })
            },

            updateModuleShow(row) {
                this.update.title = "课次信息";
                this.update.chaViurl = '';
                this.update.chalastModified = '';
                this.update.chaType = '';
                this.update.chaTime = '';
                this.update.chaSize = '';
                this.update.chaId = row.chaId;
                this.update.chaName = row.chaName;
                this.update.proShow = false;
                this.update.show = true
                this.update.disabled = false;
            },

            //新增
            addUser() {
                var courId = localStorage.getItem("courId")
                let params = new URLSearchParams()
                params.append('chaName', this.add.chaName)
                if (this.add.chaId > 0) {
                    params.append('chaParentid', this.add.chaId)
                } else {
                    params.append('chaParentid', 0)
                }

                params.append('chaCourid', courId)
                this.$refs['addForm'].validate((valid) => {
                    if (valid) {
                        axios({
                            method: 'post',
                            url: '/api/teacher/chapter/addChapters',
                            data: params,
                            headers: {
                                "Authorization": "bearer " + sessionStorage.getItem("access_token")
                            }
                        }).then(() => {

                            this.$message({
                                type: 'success',
                                message: '新增成功!',
                            });

                            this.add.show = false
                            this.queryMenu();
                            this.$refs['addForm'].resetFields();
                        })
                    } else {
                        this.$message({
                            showClose: true,
                            message: '新增失败',
                            type: 'error'
                        });
                        return false;
                    }
                });
            },
            addChapterShow(row) {
                this.add.chaId = row.chaId;
                this.add.chaName = '';
                // this.add.chaParentid="";
                this.add.show = true;
                this.add.title = "新增章节";

            },
            queryMenu() {
                var courId = localStorage.getItem("courId")


                axios({
                    method: "get",
                    url: "/api/teacher/chapter/queryChapter",
                    params: {
                        courId: courId
                    },
                }).then(res => {
                    res = res.data;
                    this.moduleData = res;
                })
            },
        },
        mounted() {

            //初始化菜单
            this.queryMenu();
            this.add.courId = localStorage.getItem("courId");

        }
    };
    var Ctor = Vue.extend(Main)
    let v = new Ctor().$mount('#app')
</script>

</html>
